#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
typedef double db;
inline int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9') { if(ch=='-')f=-1; ch=getchar(); }
	while(ch>='0'&&ch<='9') { x=(x<<1)+(x<<3)+ch-'0'; ch=getchar(); }
	return x*f;
}
const int MAXN=3e6;
char str[MAXN];
struct Splay
{
	int siz[MAXN],c[MAXN][2],fa[MAXN],cnt,rt;
	char ch[MAXN];
	void push_up(int o)
	{
		siz[o]=siz[c[o][0]]+siz[c[o][1]]+1;
		return;
	}
	void rotate(int &o,int x)
	{
		int y=fa[x],z=fa[y],dz=c[z][1]==y,dy=c[y][1]==x;
		if(o==y)o=x;
		else c[z][dz]=x;
		fa[x]=z;
		c[y][dy]=c[x][dy^1];
		fa[c[y][dy]]=y;
		c[x][dy^1]=y;
		fa[y]=x;
		push_up(y);
		return;
	}
	void splay(int &o,int x)
	{
		while(o!=x)
		{
			int y=fa[x],z=fa[y];
			if(o!=y)
			{
				if((c[y][1]==x)^(c[z][1]==y))rotate(o,x);
				else rotate(o,y);
			}
			rotate(o,x);
		}
		push_up(x);
	}
	int build(int l,int r,int lst)
	{
		if(l>r)return 0;
		int now=++cnt;
		if(l==r)
		{
			siz[now]=1;
			fa[now]=lst;
			ch[now]=str[l];
			return now;
		}
		int mid=(l+r)>>1;
		c[now][0]=build(l,mid-1,now);
		fa[now]=lst;ch[now]=str[mid];
		c[now][1]=build(mid+1,r,now);
		push_up(now);
		return now;
	}
	int find(int o,int k)
	{
		if(k<=siz[c[o][0]])return find(c[o][0],k);
		if(k==siz[c[o][0]]+1)return o;
		return find(c[o][1],k-siz[c[o][0]]-1);
	}
	void print(int o)
	{
		if(c[o][0])print(c[o][0]);
		putchar(ch[o]);
		if(c[o][1])print(c[o][1]);
		return;
	}
}T1;
int main()
{
	freopen("editor.in","r",stdin);
	freopen("editor.out","w",stdout);
	int n=read();
	T1.rt=1;T1.cnt=2;
	T1.c[1][1]=2;T1.siz[1]=2;T1.fa[2]=1;T1.siz[2]=1;
	int cur=0;
	while(n--)
	{
		char op[10];
		scanf("%s",op);
		if(op[0]=='I')
		{
			int len=read();
			for(int i=1;i<=len;++i)
			{
				scanf("%c",&str[i]);
				if(str[i]=='\n')
				{
					--i;
					continue;
				}
			}
			T1.splay(T1.rt,T1.find(T1.rt,cur+1));
			T1.splay(T1.c[T1.rt][1],T1.find(T1.rt,cur+2));
			T1.c[T1.c[T1.rt][1]][0]=T1.build(1,len,T1.c[T1.rt][1]);
			T1.push_up(T1.c[T1.rt][1]);
			T1.push_up(T1.rt);
		}
		else if(op[0]=='D')
		{
			int len=read();
			T1.splay(T1.rt,T1.find(T1.rt,cur+1));
			T1.splay(T1.c[T1.rt][1],T1.find(T1.rt,cur+len+2));
			T1.c[T1.c[T1.rt][1]][0]=0;
			T1.push_up(T1.c[T1.rt][1]);
			T1.push_up(T1.rt);
		}
		else if(op[0]=='M')cur=read();
		else if(op[0]=='P')--cur;
		else if(op[0]=='N')++cur;
		else
		{
			int len=read();
			T1.splay(T1.rt,T1.find(T1.rt,cur+1));
			T1.splay(T1.c[T1.rt][1],T1.find(T1.rt,cur+len+2));
			T1.print(T1.c[T1.c[T1.rt][1]][0]);
			puts("");
		}
	}
	return 0;
}
